package com.zx.lc.config;

import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.service.TokenStream;
import java.io.IOException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

public class SseUtil {

    public static SseEmitter createSseEmitter(TokenStream stream) {
        // sse发射器
        SseEmitter emitter = new SseEmitter();
        // 设置异步的响应回调方法
        stream.onPartialResponse((String partialResponse) -> {
                    try {
                        // 向响应中写入信息
                        emitter.send(SseEmitter.event().data(partialResponse));
                    } catch (IOException e) {
                        // 设置异常
                        emitter.completeWithError(e);
                    }
                })
                .onCompleteResponse((ChatResponse response) -> emitter.complete())
                .onError((Throwable e) -> emitter.completeWithError(e))
                .start();// 启动流程

        return emitter;
    }
}
